<?php
require_once ('..'.DIRECTORY_SEPARATOR.'initialize.php');
include_once(Utils::getPath(array('shared', 'template.php')));
include_once(Utils::getPath(array('repositories', 'userRepository.php')));
include_once(Utils::getPath(array('repositories', 'messageRepository.php')));

$template = new Template('application');
$template->initialize();

$idmsg = $_GET['id'];
if (!isset($idmsg) || !intval($_GET['id'])){
    Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
}
$userRep = new UserRepository();

$messageRep = new MessageRepository();
$msg = $messageRep->getById($idmsg);

if (!isset($msg)) {
    Utils::goToErrorPage();
}

$receiver = $msg->getIdReceiver();
$sender = $msg->getIdSender();
$subject = $msg->getSubject();
$date = $msg->getDate();
$text = $msg->getText();
$urlfriend = Utils::getUrl("user/profile.php?id=");
$toMe = $receiver == $_SESSION['authenticatedId'];

if ($sender == $_SESSION['authenticatedId']) {
    $urlfriend .= $receiver;
    $sender = $_SESSION['authenticatedUserName'];
    $receiver = $userRep->getById($receiver)->getUserName();
} else if ($receiver == $_SESSION['authenticatedId']) {
    $urlfriend .= $sender;
    $receiver = $_SESSION['authenticatedUserName'];
    $sender = $userRep->getById($sender)->getUserName();
} else {
    Utils::goToErrorPage(StatusCodes::HTTP_FORBIDDEN);
}

if ($msg->getIdReceiver() == $_SESSION['authenticatedId']) {
    $msg->setIsRead(true);
    $messageRep->persist($msg);
}
?>
<h2><?php echo $subject; ?></h2>
<?php
if ($toMe) {
    ?>
    <div class="message-username">From: <a href="<?php echo $urlfriend; ?>"><?php echo $sender; ?></a></div>
    <?php
} else {
    ?>
    <div class="message-username">To: <a href="<?php echo $urlfriend; ?>"><?php echo $receiver; ?></a></div>
    <?php
}
?>
<div class="message-datetime"><?php echo " at $date (" . Utils::ago($date) . ')'; ?></div>
<div class="message-text"><p><?php echo $text; ?></p></div>
<div class="button">
<?php
if($toMe)
{
?>
<a href="<?php echo "new.php?reply=$idmsg"; ?>">Reply</a>
    <?php
}else{?>
<a href="<?php echo "delete.php?id=$idmsg"; ?>">Delete</a>
<?php
}
?></div><?php
$template->createPage($subject);
?>